<template>
    <rx-layout>
        <div slot="left" width="250" showButton="true">
            <rx-fit>
                <a-directory-tree defaultExpandAll @select="selectCatNode">
                    <a-tree-node v-for="cat in catList" :key="cat.key" :title="$i18(cat.name,'分类名称')"
                                 style="margin-left: -25px;"/>
                </a-directory-tree>

            </rx-fit>
        </div>
        <div slot="center">
            <rx-fit>
                <div slot="toolheader" border="false" foldbtn="false">
                    <div class="table-operator">
                        <a-button-group>
                            <a-button type="primary" icon="plus" @click="onAddTree">{{$ti18('rxList.newBtn','新建')}}
                            </a-button>
                            <a-dropdown>
                                <a-button> {{$ti18('rxList.moreBtn','更多')}}
                                    <a-icon type="down"/>
                                </a-button>
                                <a-menu slot="overlay">
                                    <a-menu-item @click="transferAppMenus" icon="swap" type="primary"
                                                 v-if="selectedRowKeys && selectedRowKeys.length > 0"><i
                                        class="iconfont icondaochu"></i>{{i18n('list.transferClassify','转移分类')}}
                                    </a-menu-item>
                                    <a-menu-item key="1" @click="doImport"><i class="iconfont icondaoru"></i>{{$ti18('rxList.importBtn','导入')}}
                                    </a-menu-item>
                                    <a-menu-item @click="doExport('0')"><i class="iconfont icondaochu"></i>{{i18n('list.exportAll','导出当前所有')}}
                                    </a-menu-item>
                                    <a-menu-item key="2" @click="changeExport(exportConf)" v-if="selectedRowKeys.length > 0"
                                        alias="formRuleDelete" :butn-type="'primary'" :show-no-right="false"
                                    >
                                        <a-icon type="switcher"/>
                                        {{$ti18('rxList.changeExport','切换导出')}}
                                    </a-menu-item>
                                </a-menu>
                            </a-dropdown>
                        </a-button-group>
                        <span class="selectTypeTitle"> {{ selCatTitle }}</span>
                    </div>
                </div>
                <rx-grid
                    ref="categoryTable"
                    :columns="columns"
                    :bordered="true"
                    :dataSource="sysTreeData"
                    :allowRowSelect="true"
                    :multiSelect="true"
                    :resultAsTree="true"
                    id-field="treeId"
                    :expandIconColumnIndex="1"
                    :showPage="false"
                    @selectChange="onSelectChange"
                    :ellipsis="true"
                >
                    <span slot="exportApp">
                         {{ exportI18n('export.isExport','导出') }}
                        <export-app/>
                    </span>
                    <span slot="name" slot-scope="{text,record}">
                         {{$i18(text,'分类名称')}}
                    </span>
                    <span slot="appName" slot-scope="{text,record}">
                         {{$i18(record.appName,"应用名称")}}
                    </span>
                    <span slot="isExport" slot-scope="{ text, record }">
                        <a-tag :color="text == 1 ? 'green' : 'red'">
                            <span>{{ text == 1 ? exportI18n('export.yes','是') : exportI18n('export.no','否') }}</span>
                        </a-tag>
                    </span>
                    <span slot="action" slot-scope="{text,record}">
                        <span @click="onEdit(record)">{{$ti18('rxList.editBtn','编辑')}}</span>
                        <span @click="onAddSibling(record)" :title="i18n('list.addSibling','添加同级')">{{i18n('list.addSibling','添加同级')}}</span>
                        <span @click="onAddChild(record)" :title="i18n('list.addChild','添加子级')">{{i18n('list.addChild','添加子级')}}</span>
                        <span @click="transportTo(record)">{{i18n('list.transferTo','转移')}}</span>
                        <span @click="onDel(record)">{{$ti18('rxList.delBtn','删除')}}</span>
                        <span @click="setExport(record,exportConf)">{{record.isExport == 1 ? exportI18n('export.noExport','不导出') : exportI18n('export.exported','导出')}}</span>
                    </span>
                </rx-grid>
            </rx-fit>
        </div>
    </rx-layout>

</template>

<script>
    import SysTreeApi from '@/api/system/core/sysTree'
    import SysTreeCatApi from '@/api/system/core/sysTreeCat'
    import SysTreeEdit from './SysTreeEdit'
    import {RxLayout, RxFit, Util, RxGrid, App} from "@lowcode/jpaas-common-lib";
    import FormImport from '@/views/modules/form/core/FormImport'
    import SysTreeChange from './SysTreeChange';
    import exportApp from "@/views/modules/share/exportApp";
    import switchExport from "@/utils/switchExport";

    export default {
        name: 'SysTreeList',
        mixins: [App,switchExport],
        components: {
            SysTreeEdit,
            RxLayout,
            RxFit,
            FormImport,
            RxGrid,
            exportApp
        },
        data() {
            return {
                sysTreeData: [],
                sysTreeAllData: [],
                //树分类
                catList: [],
                selCatTitle: this.i18n('list.selectTiTle', '未选择分类'),
                selCatDefId: '',//选择分类Id
                // 表头
                columns: [
                    {
                        title: this.i18n('form.name', '名称'),
                        dataIndex: 'name',
                        width: 120,
                        scopedSlots: {customRender: 'name'}
                    },
                    {
                        title: this.i18n('form.alias', '节点别名'),
                        dataIndex: 'alias',
                        width: 120
                    },
                    {
                        title: this.i18n('form.appName', '所属应用'),
                        dataIndex: 'appName',
                        width: 120,
                        scopedSlots: {customRender: 'appName'}
                    },
                    {
                        dataIndex: 'isExport',
                        slots: {title: 'exportApp'},
                        width: 100,
                        scopedSlots: {customRender: 'isExport'}
                    },
                    {
                        title: this.$ti18('rxForm.createTime', '创建时间'),
                        dataIndex: 'createTime',
                        sorter: true,
                        sortField: 'CREATE_TIME_',
                        width: 150
                    },
                    {
                        title: this.$ti18('rxList.action', '操作'),
                        dataIndex: 'action',
                        width: 120,
                        scopedSlots: {customRender: 'action'}
                    }
                ],
                curRow: {},
                purl: "",

                ResData: [],
                // 加载数据方法 必须为 Promise 对象
                selectedRowKeys: [],
                selectedRows: [],
                selectedApiRowKeys: [],
                selectedApiRows: [],
                /**
                 * 导出配置
                 */
                exportConf:{
                    Api:SysTreeApi,
                    id:"pkId",
                    table:"categoryTable"
                }
            }
        },
        created() {
            this.removeAppColumn()
            SysTreeCatApi.getCatList().then(res => {
                if (res.length>0){
                    res=res.filter(item => item.key!='APP')
                }
                this.catList = res;
            });
        },
        computed: {
            categoryTable() {
                return this.$refs.categoryTable;
            }
        },
        methods: {
            removeAppColumn(){
                var flag=true
                if (!this.curApp.appId){
                    flag=true
                }
                if (this.curApp.appId!='' && this.curApp.appId!=0){
                    flag=false
                }
                if (!flag){
                    this.columns=this.columns.filter(column=>column.dataIndex!="appName")
                }

            },
            i18n(name, text, key) {
                return this.$ti18(name, text, "SysTree", key);
            },
            exportI18n(name, text, key) {
                return this.$ti18(name, text, "appExport", key);
            },
            transferAppMenus() {
                var self = this;
                var conf = {
                    component: SysTreeChange,
                    title: this.i18n('transfer.transferTitle', '转移到'),
                    curVm: self,
                    widthHeight: ['400px', '550px'],
                    data: {
                        multiSelect: false,
                        sysTreeData: this.sysTreeAllData
                    }
                };
                Util.open(conf, function (action) {
                    if (action != 'ok') {
                        return;
                    }
                    var selectTrees = this.getSelectTree();
                    if (!selectTrees || selectTrees == 0) {
                        this.$message.error(this.i18n('transfer.selectTips', '请选择分类！'));
                        return;
                    }
                    self.toMoveMenu(self.selectedRows, selectTrees[0]);
                });
            },
            transportTo(record) {
                var self = this;
                var conf = {
                    component: SysTreeChange,
                    title: this.i18n('transfer.transferTitle', '转移到'),
                    curVm: self,
                    widthHeight: ['400px', '550px'],
                    data: {
                        multiSelect: false,
                        sysTreeData: this.sysTreeAllData
                    }
                };
                Util.open(conf, function (action) {
                    if (action !== 'ok') { return }
                    let selectTrees = this.getSelectTree();
                    let list = [];
                    list.push(record);
                    self.toMoveMenu(list, selectTrees[0])
                });
            },
            toMoveMenu(records, changeTree) {
                debugger
                let self = this, treeIds = "";
                for (let i = 0; i < records.length; i++) {
                    let record = records[i];
                    //自己无需操作
                    if (record.treeId === changeTree.treeId) {
                        this.$message.error("【" + record.treeId + "】【" + this.$i18(record.name) + "】" + this.i18n('transfer.moveTips1', '分类无需转移给自己！'));
                        return;
                    }
                    //父不可以转到子
                    if (record.treeId === changeTree.parentId) {
                        this.$message.error("【" + record.treeId + "】【" + this.$i18(record.name) + "】" + this.i18n('transfer.moveTips2', '父分类不可以转移到子分类') + "【" + this.$i18(changeTree.name) + "】，" + this.i18n('transfer.moveTips3', '请先将子分类迁移后再操作！'));
                        return;
                    }
                    //不可以转移到孙级分类
                    if (changeTree.path.indexOf(record.treeId) > -1) {
                        this.$message.error("【" + record.treeId + "】【" + this.$i18(record.name) + "】" + this.i18n('transfer.moveTips4', '分类不可以转移到孙级分类') + "【" + this.$i18(changeTree.name) + "】，" + this.i18n('transfer.moveTips5', '请先将孙级分类迁移后再操作！'));
                        return;
                    }
                    //相同位置无需再转移
                    if (record.parentId === changeTree.treeId) {
                        this.$message.error("【" + record.treeId + "】【" + this.$i18(record.name) + "】" + this.i18n('transfer.moveTips6', '相同位置') + "【" + this.$i18(changeTree.name) + "】，" + this.i18n('transfer.moveTips7', '无需再转移！'));
                        return;
                    }
                    treeIds += record.treeId + ",";
                }

                treeIds = treeIds.substring(0, treeIds.lastIndexOf(","));

                SysTreeApi.toMoveMenu({
                    treeIds: treeIds,
                    targetId: changeTree.treeId,
                }).then(res => {
                    if (res.success) {
                        self.loadData();
                    }
                });
            },
            onSelectChange(selectedRowKeys, selectedRows) {
                this.selectedRowKeys = selectedRowKeys;
                this.selectedRows = selectedRows;
            },
            modtclick(data, title, operator) {
                if (!this.selCatKey || this.selCatKey == '') {
                    this.$message.warning(this.i18n('msa.selKeyTips', '请选择分类key'));
                    return;
                }
                var conf = {
                    curVm: this,
                    data: {data: data},
                    widthHeight: ['800px', '450px'],
                    component: SysTreeEdit,
                    title: title
                };
                //编辑
                if (data.pkId) {
                    conf.data.pkId = data.pkId;
                }
                var self_ = this;
                Util.open(conf, function (action) {
                    if (action != "ok") {
                        return;
                    }
                    var pkId = this.resultData.pkId;
                    SysTreeApi.getById(pkId).then(res => {
                        var row = res.data;
                        switch (operator) {
                            case "add":
                                self_.addNode(row);
                                break
                            case "edit":
                                self_.categoryTable.updateRow(self_.curRow, row);
                                break;
                            case "addchild":
                                if (!self_.curRow.children) {
                                    self_.curRow.children = [];
                                } else {
                                    self_.addNode(row, self_.curRow);
                                }
                                break;
                            case "addSibling":
                                var parentNode = self_.getParentNode(self_.curRow);
                                self_.addNode(row, parentNode);
                                break;
                        }
                        self_.loadData();
                    })
                });
            },
            addNode(node, parentNode, index) {
                var ary = [];
                if (parentNode) {
                    if (parentNode.children) {
                        ary = parentNode.children;
                    } else {
                        ary = parentNode.children = [];
                    }
                } else {
                    ary = this.sysTreeData;
                }
                this.categoryTable.addItem(ary, node, index);
                this.loadData();
            },
            getParentNode(node) {
                var self = this;
                var parents = this.findNodes(function (data) {
                    if (data['treeId'] == node['parentId']) return true;
                })
                if (parents.length > 0) {
                    return parents[0];
                }
                return null;
            },
            findNodes(fn) {
                var nodes = [];
                this.categoryTable.findRow(nodes, this.sysTreeData, fn);
                return this.categoryTable.delOther(nodes);
            },
            selectCatNode(keys, e) {
                this.selCatTitle = e.node.title;
                this.selCatKey = keys[0];
                this.loadData();
            },
            // 加载数据方法 必须为 Promise 对象
            loadData() {
                if (!this.selCatKey || this.selCatKey == '') {
                    return;
                }
                var self_ = this;
                SysTreeApi.getByCatKeyAndParentId(self_.selCatKey, self_.curApp.appId, "getAll").then(res => {
                    self_.sysTreeAllData = res;
                    let listData = Util.treeData(res, 'treeId');
                    self_.sysTreeData = listData;
                    //刷新下
                    this.categoryTable.onRefresh();
                })
            },
            //添加树
            onAddTree() {
                var title = this.i18n('list.newTitle', '新建分类')
                this.modtclick({catKey: this.selCatKey, parentName: '', parentId: '0'}, title, "add")
            },

            onEdit(record) {
                var title = this.i18n('list.editTitle', '编辑');
                this.curRow = record;
                this.modtclick(record, title, "edit")
            },

            onAddChild(record) {
                var rs = Object.assign({parentName: record.name, parentId: record.treeId, catKey: record.catKey});
                var title = this.i18n('list.addChild', '添加子级');
                this.curRow = record;
                this.modtclick(rs, title, "addchild")
            },

            //添加同级兄弟
            onAddSibling(record) {
                var title = this.i18n('list.addSibling', '添加同级')
                this.curRow = record;
                if (record.parentId && record.parentId != '0') {
                    //取得上级的数据
                    SysTreeApi.get(record.parentId).then(response => {
                        var data = response.data;
                        var rs = Object.assign({parentName: data.name, parentId: data.treeId, catKey: record.catKey});
                        this.modtclick(rs, title, "addSibling")
                    });
                } else {
                    var catKey = record.catKey;
                    if (!catKey) {
                        catKey = this.selCatKey;
                    }
                    var rs = Object.assign({parentName: '', parentId: '0', catKey: catKey});
                    this.modtclick(rs, title, "addSibling")
                }
            },
            onDel(record) {
                let self_ = this
                this.$confirm({
                    title: this.$ti18('rxMsa.actionTips', '操作提示'),
                    content: this.$ti18('rxMsa.delInfo', '您确定...'),
                    okText: this.$ti18('rxForm.ackBtn', '确认'),
                    cancelText: this.$ti18('rxForm.cancelBtn', '取消'),
                    onOk() {
                        SysTreeApi.delByTreeId({treeId: record.treeId}).then(res => {
                            if (res.success && res.code == 200) {
                                self_.removeNode(record);
                            }
                        })
                    },
                    onCancel() {
                    }
                })
            },
            removeNode(node) {
                var rowKeys;
                if (node) {
                    rowKeys = [node['treeId']];
                }
                this.categoryTable.removeRows(rowKeys);
            },
            doExport(isSelected) {
                var exportList = [];
                SysTreeApi.getByCatKey(this.selCatKey, this.curApp.appId).then(res => {
                    exportList = res;
                    if (exportList == "") {
                        this.$warning({
                            title: this.$ti18('rxMsa.masWarn.delInfo', '警告'),
                            content: this.i18n('msa.exportTips', '该分类没有数据！'),
                        });
                        return;
                    }
                    var solutionIds = [];
                    exportList.forEach(item => {
                        solutionIds.push(item.treeId);
                    });
                    SysTreeApi.doExport(solutionIds);
                })
            },

            doImport() {
                var catId = this.selCatKey;
                Util.open({
                    component: FormImport,
                    curVm: this,
                    widthHeight: ['800px', '600px'],
                    zIndex: 9,
                    title: this.i18n('list.importTiTle', '系统分类树导入'),
                    data: {
                        treeId: catId,
                        callback: function (params) {
                            let self = this;
                            SysTreeApi.doImport(params).then(res => {
                                this.isSpinning = false;
                                if (!res.success) {
                                    self.$confirm({
                                        title: self.$ti18('rxMsa.masWarn.delInfo', '警告'),
                                        content: self.$ti18('msa.importError', '导入失败！', "SysTree"),
                                        okText: self.$ti18('rxForm.ackBtn', '确认'),
                                        cancelText: self.$ti18('rxForm.cancelBtn', '取消'),
                                    });
                                    return;
                                }
                                self.getUpdataSqls(res.data);
                            });
                        }
                    }
                }, function (action) {
                });
            },
        }
    }
</script>
<style scoped>
    .rx-card,
    .ant-card {
        display: flex;
        flex-direction: column;
        height: 100%;
        box-sizing: border-box;
    }

    * >>> .ant-card-body {
        flex: 1;
        overflow: auto;
    }

    * >>> .ant-table-fixed-header .ant-table-scroll .ant-table-header {
        padding-bottom: 0;
    }

    .selectTypeTitle {
        display: inline-block;
        height: 32px;
        line-height: 32px;
        padding-left: 20px;
        border: 1px dashed #ddd;
        padding-right: 20px;
        margin-left: 20px;
        vertical-align: middle;
    }
</style>

